import 'dart:async';
import 'dart:convert';
import 'package:agora_rtm/agora_rtm.dart';
import 'package:gameplay_flutter/lib_rtc/mixin/rtm_message_mixin.dart';

import '../../lib_runtime/global_config.dart';
import '../../lib_runtime/logger.dart';

class RtmManager with RtmMessageMixin {
  static String get appId => GlobalConfig.isOfficial
      ? '86b2ac3562e343f5af1acd303e188c6c'
      : '86b2ac3562e343f5af1acd303e188c6c';

  static final RtmManager instance = RtmManager._();

  /// 保存一下用户当前的 channel(房间id)
  late String currentChannel;
  late RtmClient _rtmClient;

  @override // 实现Mixin要求的抽象getter
  RtmClient get rtmClient => _rtmClient;

  // RtmClient get rtmClient => _rtmClient;

  /// 是否初始化
  bool _inited = false;

  /// 是否加入频道
  bool _joined = false;

  RtmManager._();

  Future<void> init(String token, int userId, String channel) async {
    log('RtMManager.init  userId: $userId, _inited: $_inited, appId: $appId');

    if (_inited ||
        appId.isEmpty ||
        userId <= 0 /*|| (rtmToken?.isEmpty ?? true) */) {
      log('RtmManager.init ignore!!!');
      return;
    }
    currentChannel = channel;
    await _initEngine(appId, userId.toString());

    log('RtmManager init done ${userId}');
    _inited = true;
  }

  Future<void> _initEngine(String appId, String userId) async {
    try {
      const logConfig =
          RtmLogConfig(filePath: './rtm_logfile/', fileSizeInKB: 1024);

      const rtmConfig = RtmConfig(logConfig: logConfig);

      // create rtm client
      final (status, client) = await RTM(appId, userId, config: rtmConfig);
      if (status.error == true) {
        print(
            '${status.operation} failed due to ${status.reason}, error code: ${status.errorCode}');
      } else {
        // rtmClient = client;
        _rtmClient = client;
        print('Initialize success!');
      }
      // 初始化后启动消息监听
      initRtmMessageListener(); // <-- 新增此行
    } catch (e) {
      print('Initialize falid!:${e}');
    }
  }

  loginRtmChannel(String rtmToken) async {
    // log('Join rtm channel with appid: $appId joined: $_joined');

    if (_joined) return;

    try {
      var (status, response) = await rtmClient.login(rtmToken);
      if (status.error == true) {
        _joined = false;
        print(
            '${status.operation} failed due to ${status.reason}, error code: ${status.errorCode}');
      } else {
        print('login RTM success!');

        /// 登录成功，就立即订阅当前的频道
        subscribe();
        _joined = true;
      }
    } catch (e) {
      print('Failed to login: $e');
    }
  }

  /// 发送消息
  Future<void> publish(String msg) async {
    if (currentChannel.isEmpty) {
      print('当前rtc channel 为空');
      return;
    }

    try {
      var (status, response) = await rtmClient.publish(currentChannel, msg,
          channelType: RtmChannelType.message);
      if (status.error == true) {
        print(
            '${status.operation} failed, errorCode: ${status.errorCode}, due to ${status.reason}');
      } else {
        print('${status.operation} success! message $msg');
      }
    } catch (e) {
      print('Failed to publish message: $e');
    }
    // await Future.delayed(Duration(seconds: 1));
  }

  /// 收到消息
  Future<void> subscribe() async {
    if (currentChannel.isEmpty) {
      print('当前rtc channel 为空');
      return;
    }

    try {
      // subscribe to 'getting-started' channel
      var (status, response) = await rtmClient.subscribe(currentChannel);
      if (status.error == true) {
        print(
            '${status.operation} failed due to ${status.reason}, error code: ${status.errorCode}');
      } else {
        print('subscribe channel: ${currentChannel} success!');
      }
    } catch (e) {
      print('Failed to subscribe channel: $e');
    }
  }

  /// channelName 当前房间号
  Future<void> leaveRtmChannel() async {
    RLog.i('$runtimeType leaveChannel');
    await _dispose();
  }

  /// channelName 当前房间号
  Future<void> _dispose() async {
    _joined = false;
    _inited = false;

    if (currentChannel.isEmpty) {
      print('当前rtc channel 为空');
      return;
    }
    try {
      // unsubscribe channel
      var (status, response) = await rtmClient.unsubscribe(currentChannel);
      if (status.error == true) {
        print(
            '${status.operation} failed due to ${status.reason}, error code: ${status.errorCode}');
      } else {
        print('unsubscribe success!');
      }
    } on Exception catch (e) {
      print('something went wrong with logout: $e');
    }

    try {
      // logout rtm service
      var (status, response) = await rtmClient.logout();
      if (status.error == true) {
        print(
            '${status.operation} failed due to ${status.reason}, error code: ${status.errorCode}');
      } else {
        print('logout RTM success!');
      }
    } catch (e) {
      print('something went wrong with logout: $e');
    }
  }

  /// 离开频道时清理
  Future<void> dispose() async {
    disposeRtmMessageListeners();
  }

  log(String msg) => RLog.d('RtcManager: $msg');
}
